package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-12-07
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    //注入
    //@Resource
    //@Qualifier
    @Autowired
    private DictListener dictListener;

    //懒加载: 每次查询一层数据
    //SELECT * FROM dict WHERE parent_id=1
    //dict::1  : value值::方法id值 构成redis的key
    // dict::selectIndexList86
    //@Cacheable(value = "dict", key = "'selectIndexList'+#id")
    @Cacheable(value = "dict")
    @Override
    public List<Dict> findDataChild(Long id) {
        //封装条件
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        // 处理hasChildren"值，如果数据有下一层数据hasChildren"值true，否则false
        //对查询出来dictList集合进行遍历
        //遍历之后得到集合每个dict对象
        //查询dict下面是否有下一层数据，如果有hasChildren"值设置true，否则false
        for(Dict dict : dictList) {
            //判断每个dict是否有下一层数据
            //根据dict的id查询下一层是否有数据
            //获取dict的id
            Long dictId = dict.getId();
            //查询判断
            boolean isChild = this.isHasChildren(dictId);
            //设置到dict对象里面
            dict.setHasChildren(isChild);
        }
        return dictList;
    }

    //数据字典导出
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //1 设置下载需要参数
            //设置mime类型
            response.setContentType("application/vnd.ms-excel");
            //设置编码
            response.setCharacterEncoding("utf-8");
            //设置响应头
            //中文乱码处理，编码处理
            String fileName = URLEncoder.encode("数据字典", "utf-8");
            response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx");

            //2 查询数据库表dict，把dict表所有数据查询出来
            List<Dict> dictList = baseMapper.selectList(null);

            // Dict  DictEeVo
            // 把List<Dict>  变成  List<DictEeVo>
            List<DictEeVo> dictEeVoList = new ArrayList<>();
            for(Dict dict : dictList) {  //遍历 dictList.每个dict对象
                //从每个dict获取数据
//                Long id = dict.getId();
//                Long parentId = dict.getParentId();
//                String name = dict.getName();
//                String value = dict.getValue();
//                String dictCode = dict.getDictCode();
//
//                //创建DictEeVo对象
//                DictEeVo dictEeVo = new DictEeVo();
//                //设置到dictEeVo里面
//                dictEeVo.setId(id);
//                dictEeVo.setParentId(parentId);
//                dictEeVo.setName(name);
//                dictEeVo.setValue(value);
//                dictEeVo.setDictCode(dictCode);

                //创建DictEeVo对象
                DictEeVo dictEeVo = new DictEeVo();
                //使用工具类
                //把dict值 复制 到dictEeVo里面
                BeanUtils.copyProperties(dict,dictEeVo);
                //放到list集合
                dictEeVoList.add(dictEeVo);
            }

            //3 使用EasyExcel进行写操作
            // List<DictEeVo>
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("数据字典")
                    .doWrite(dictEeVoList);
        }catch (Exception e) {
            throw new YyghException(20001,"数据字典导出失败");
        }
    }

    //数据字典导入功能
    //dict::1
    //新增数据，清空缓存，重新redis加入数据
    @CacheEvict(value = "dict",allEntries = true)
    @Override
    public void importData(MultipartFile file) {
        //调用EasyExcel的方法实现
        try {
            EasyExcel.read(file.getInputStream(),
                           DictEeVo.class, dictListener).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //根据编号获取名称
    @Override
    public String getNameByCode(String dictCode, String value) {
        //判断dcitcode是否为空，为空 value唯一，不为空 value不唯一
        if(StringUtils.isEmpty(dictCode)) { //value唯一，直接查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            if(dict == null) {
                throw new YyghException(20001,"没有查询到数据");
            }
            //返回编号对应名称
            return dict.getName();
        } else {//value不唯一，使用dictcode
            //# 第一步 根据dict_code值查询医院等级层id值
            //SELECT * FROM dict WHERE dict_code='Hostype' # 10000
            QueryWrapper<Dict> dictCodeWrapper = new QueryWrapper<>();
            dictCodeWrapper.eq("dict_code",dictCode);
            Dict dictCodeObject = baseMapper.selectOne(dictCodeWrapper);

//            # 第二步 根据10000 + 1 两个值查询医院具体等级
//            SELECT * FROM dict WHERE parent_id=10000 AND VALUE=1
            QueryWrapper<Dict> dictWrapper = new QueryWrapper<>();
            dictWrapper.eq("parent_id",dictCodeObject.getId());
            dictWrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(dictWrapper);
            return dict.getName();
        }
    }

    //所有省  所有等级  所有民族
    @Override
    public List<Dict> selectAllDataByDictCode(String dictCode) {
//        SELECT * FROM dict WHERE dict_code='Province' # 86
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict dictParent = baseMapper.selectOne(wrapper);

//        SELECT * FROM dict WHERE parent_id=86
        QueryWrapper<Dict> wrapperDict = new QueryWrapper<>();
        wrapperDict.eq("parent_id",dictParent.getId());
        List<Dict> dictList = baseMapper.selectList(wrapperDict);
        return dictList;
    }

    //查询dict下面是否有下一层数据
    private boolean isHasChildren(Long dictId) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",dictId);
        Integer count = baseMapper.selectCount(wrapper);
        //  3>0 true    0>0 false
        return count>0;
    }
}
